<template>
    <ChatPage v-if="flag" :chatInfos="chatInfos"></ChatPage>
    <div class="bottomContainer">
        <Function></Function>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import useUserStore from '@/store/modules/user'
import useMessagesStore from '@/store/modules/messages'
import { conversation, messages, chatInfo } from '@/api/messages/type'

//控制组件是否销毁刷新
let flag = ref<boolean>(true)
const $route = useRoute()
const userStore = useUserStore()
const messagesStore = useMessagesStore()
//有聊天记录时对时间标签时间戳的记忆
let timeInfo = ref<number>(0)
//聊天页面显示的对话和时间标签(未经过虚拟列表处理)
let chatInfos = ref<chatInfo[]>([])
//展示的聊天消息
let showMessages = ref<messages[]>([])

// 获取图片的自然宽高，并将其应用到el-image的宽高上。
const handleImageLoad = (maxSize: number, width: number = 0, height: number = 0) => {
    if (width > maxSize || height > maxSize) {
        //取缩小比例较小的倍数
        const scale = Math.min(maxSize / width, maxSize / height)
        width = width * scale
        height = height * scale
    }

    return { width, height }
}

//匹配并返回仓库中对应好友的聊天信息
const searchMessages = (conversationId: number) => {
    if (messagesStore.conversations.length === 0) {
        return []
    }
    let friendconversation: conversation = messagesStore.conversations.find(
        (item: conversation) => {
            return item.conversation_id === conversationId
        },
    )!
    if (friendconversation.messages.length > 0) {
        return friendconversation.messages
    } else {
        return []
    }
}

//增加一条聊天信息的展示
const checkMessage = (message: messages) => {
    const timeDiff = message.send_time - timeInfo.value
    if (timeInfo.value === 0 || timeDiff >= 600000) {
        chatInfos.value.unshift({
            type: 'ChatTime',
            content: message.send_time,
            id: `time-${message.send_time}`,
        })
        timeInfo.value = message.send_time
    }

    const isCurrentUser = userStore.userId === message.sender_id
    const imgWidthAndHeight = handleImageLoad(288, message.file_width, message.file_height)
    const newMessage = {
        type: isCurrentUser ? 'ChatMessageRight' : 'ChatMessageLeft',
        message_type: message.message_type,
        id: message.message_id,
        content: message.message_content,
        avatar: isCurrentUser ? userStore.avatar : messagesStore.chattingFriend?.avatar,
        media_url: message.media_url,
        duration: message.duration,
        media_size: message.media_size,
        preview_url: message.preview_url,
        file_width: imgWidthAndHeight.width,
        file_height: imgWidthAndHeight.height,
    }
    chatInfos.value.unshift(newMessage)
}

//遍历所有聊天信息展示在页面上
const showElement = (showMessages: messages[]) => {
    if (showMessages.length === 0) {
        return
    }

    for (const item of showMessages) {
        checkMessage(item)
    }
}

//监听仓库数据实现新消息显示
watch(
    () => messagesStore.conversations,
    () => {
        showMessages.value = searchMessages(messagesStore.chattingFriend?.conversation_id as number)
        if (showMessages.value.length !== 0) {
            let newestMessage: messages = showMessages.value.at(-1)!
            checkMessage(newestMessage)
        }
    },
    { deep: true },
)

//监听路由数据是否发生变化，如果发生变化，刷新聊天页面
watch(
    () => $route.path,
    () => {
        flag.value = false
        showMessages.value = searchMessages(messagesStore.chattingFriend?.conversation_id as number)
        timeInfo.value = 0
        chatInfos.value = []

        if (showMessages.value.length !== 0) {
            showElement(showMessages.value)
        }
        nextTick(() => {
            flag.value = true
        })
    },
)

//格式化聊天记录数据
onMounted(() => {
    showMessages.value = searchMessages(messagesStore.chattingFriend?.conversation_id as number)
    if (showMessages.value.length !== 0) {
        showElement(showMessages.value)
    }
})
</script>

<style scoped lang="scss">
.bottomContainer {
    width: 100%;
    height: $base-function-height;
}
</style>
